<template>
  <div>
    <el-cascader v-model="value" :options="cities" style="width: 100%;" @change="changeCity" />
  </div>
</template>

<script>
import city from '@/api/city'
export default {
  name: 'City',
  emits: ['change'],
  props: {
    city: {
      type: Number,
      default: 0
    },
    len: {
      type: Number,
      default: 3
    }
  },
  data() {
    return {
      value: [],
      cities: []
    }
  },
  watch: {
    city() {
      if (this.city > 0) {
        this.getCity()
      }
    }
  },
  created() {
    this.getCity()
  },
  methods: {
    getCity() {
      city.index(0).then(res => {
        const cities = res.data
        console.log(this.len)
        // 省份
        for (const a in cities) {
          if (this.len === 1) {
            delete cities[a].children
            continue
          }
          // 城市
          for (const b in cities[a].children) {
            if (this.len === 2) {
              delete cities[a].children[b].children
            }
          }
        }
        this.cities = cities
        console.log(this.cities)
        this.value = this.findCity(this.city)
      })
    },
    changeCity(e) {
      console.log('改变城市')
      console.log(e)
      this.$emit('change', e[this.len - 1])
    },
    findCity(cityId) {
      console.log('当前城市')
      console.log(cityId)
      cityId = parseInt(cityId)
      if (cityId === 0) {
        return []
      }
      // 只需要最高层
      for (const p of this.cities) {
        if (this.len === 1) {
          if (p.value === cityId) {
            return [p.value]
          }
          continue
        }
        // 只需要第二层
        for (const c of p.children) {
          if (this.len === 2) {
            if (c.value === cityId) {
              return [p.value, c.value]
            }
            continue
          }

          for (const r of c.children) {
            if (r.value === cityId) {
              return [p.value, c.value, r.value]
            }
          }
        }
      }
      return []
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
